import React, { useState, useEffect } from 'react'
import { useSearchParams } from 'react-router-dom'
import { usePapers } from '../hooks/usePapers'
import { useSubscription } from '../contexts/AuthProvider'
import { SearchBar } from '../components/search/SearchBar'
import { FilterPanel } from '../components/browse/FilterPanel'
import { SortOptions } from '../components/browse/SortOptions'
import { PaperCard } from '../components/papers/PaperCard'
import { Button } from '../components/ui/Button'
import { Badge } from '../components/ui/Badge'
import { LoadingSpinner } from '../components/ui/LoadingSpinner'
import { EmptyState } from '../components/ui/EmptyState'
import { 
  Search, 
  Filter, 
  Grid, 
  List,
  Crown
} from 'lucide-react'

export function Browse() {
  const [searchParams, setSearchParams] = useSearchParams()
  const { subscription, canUseFeature } = useSubscription()
  const { 
    papers, 
    loading, 
    totalCount, 
    hasMore, 
    fetchPapers, 
    bookmarkPaper,
    loadMore 
  } = usePapers()

  const [query, setQuery] = useState(searchParams.get('q') || '')
  const [viewMode, setViewMode] = useState<'grid' | 'list'>('list')
  const [showFilters, setShowFilters] = useState(false)
  const [filters, setFilters] = useState({
    categories: [] as string[],
    dateRange: 'all',
    sortBy: 'relevance',
    authors: [] as string[]
  })

  useEffect(() => {
    const initialQuery = searchParams.get('q') || ''
    const alertId = searchParams.get('alert')
    
    if (initialQuery || alertId) {
      setQuery(initialQuery)
      fetchPapers(initialQuery, { ...filters, alertId })
    } else {
      // Load trending papers by default
      fetchPapers('', { ...filters, trending: true })
    }
  }, [searchParams, fetchPapers, filters])

  const handleSearch = (searchQuery: string) => {
    setQuery(searchQuery)
    const newParams = new URLSearchParams()
    if (searchQuery) newParams.set('q', searchQuery)
    setSearchParams(newParams)
    fetchPapers(searchQuery, filters)
  }

  const handleFilterChange = (newFilters: typeof filters) => {
    setFilters(newFilters)
    fetchPapers(query, newFilters)
  }

  const handleBookmark = async (paperId: string) => {
    if (!canUseFeature('max_saved_papers', subscription?.usage_metrics?.saved_papers_count || 0)) {
      // Show upgrade modal
      window.location.href = '/app/subscription?reason=bookmark_limit'
      return
    }
    
    await bookmarkPaper(paperId)
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between space-y-4 lg:space-y-0">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Browse Papers</h1>
          <p className="text-gray-600">
            Discover the latest research across all ArXiv categories
          </p>
        </div>
        
        {/* Advanced Search CTA for free users */}
        {!canUseFeature('advanced_search') && (
          <div className="flex items-center space-x-2">
            <Badge variant="outline" className="text-xs">
              <Crown className="h-3 w-3 mr-1" />
              Premium Feature
            </Badge>
            <Button 
              variant="outline" 
              size="sm"
              onClick={() => window.location.href = '/app/subscription?feature=advanced_search'}
            >
              Upgrade for Advanced Search
            </Button>
          </div>
        )}
      </div>

      {/* Search and Controls */}
      <div className="bg-white rounded-lg border border-gray-200 p-4">
        <div className="flex flex-col lg:flex-row lg:items-center space-y-4 lg:space-y-0 lg:space-x-4">
          <div className="flex-1">
            <SearchBar
              placeholder="Search papers by title, author, abstract, or arXiv ID..."
              onSearch={handleSearch}
            />
          </div>
          
          <div className="flex items-center space-x-2">
            <Button
              variant="outline"
              size="sm"
              onClick={() => setShowFilters(!showFilters)}
              className="flex items-center"
            >
              <Filter className="h-4 w-4 mr-2" />
              Filters
              {(filters.categories.length > 0 || filters.authors.length > 0 || filters.dateRange !== 'all') && (
                <Badge variant="destructive" className="ml-2 text-xs">
                  {filters.categories.length + filters.authors.length + (filters.dateRange !== 'all' ? 1 : 0)}
                </Badge>
              )}
            </Button>
            
            <div className="flex items-center border border-gray-300 rounded-md">
              <Button
                variant={viewMode === 'list' ? 'default' : 'ghost'}
                size="sm"
                onClick={() => setViewMode('list')}
                className="rounded-r-none"
              >
                <List className="h-4 w-4" />
              </Button>
              <Button
                variant={viewMode === 'grid' ? 'default' : 'ghost'}
                size="sm"
                onClick={() => setViewMode('grid')}
                className="rounded-l-none border-l border-gray-300"
              >
                <Grid className="h-4 w-4" />
              </Button>
            </div>
          </div>
        </div>
        
        {/* Results summary */}
        <div className="flex items-center justify-between mt-4 pt-4 border-t border-gray-200">
          <div className="flex items-center space-x-4 text-sm text-gray-600">
            {totalCount > 0 && (
              <span>{totalCount.toLocaleString()} papers found</span>
            )}
            {query && (
              <span>for "{query}"</span>
            )}
          </div>
          
          <SortOptions
            value={filters.sortBy}
            onChange={(sortBy) => handleFilterChange({ ...filters, sortBy })}
          />
        </div>
      </div>

      {/* Filters Panel */}
      {showFilters && (
        <FilterPanel
          filters={filters}
          onChange={handleFilterChange}
          onClose={() => setShowFilters(false)}
          isPremiumUser={canUseFeature('advanced_search')}
        />
      )}

      {/* Results */}
      <div className="bg-white rounded-lg border border-gray-200">
        {loading && papers.length === 0 ? (
          <div className="flex items-center justify-center py-12">
            <LoadingSpinner size="lg" />
          </div>
        ) : papers.length === 0 ? (
          <EmptyState
            icon={<Search className="h-12 w-12 text-gray-400" />}
            title="No papers found"
            description={
              query 
                ? `No papers match your search for "${query}". Try different keywords or adjust your filters.`
                : "No papers are available right now. Try searching or adjusting your filters."
            }
            action={
              <Button onClick={() => handleSearch('')}>
                Browse All Papers
              </Button>
            }
          />
        ) : (
          <div className="divide-y divide-gray-200">
            {/* Papers list/grid */}
            <div className={
              viewMode === 'grid' 
                ? "grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-4 p-4"
                : "divide-y divide-gray-100"
            }>
              {papers.map(paper => (
                <div 
                  key={paper.id}
                  className={viewMode === 'list' ? "p-4" : ""}
                >
                  <PaperCard
                    paper={paper}
                    variant={viewMode === 'grid' ? 'default' : 'compact'}
                    showBookmark
                    onBookmark={handleBookmark}
                  />
                </div>
              ))}
            </div>

            {/* Load more */}
            {hasMore && (
              <div className="p-4 text-center border-t border-gray-100">
                <Button
                  variant="outline"
                  onClick={loadMore}
                  disabled={loading}
                >
                  {loading ? (
                    <>
                      <LoadingSpinner size="sm" className="mr-2" />
                      Loading...
                    </>
                  ) : (
                    'Load More Papers'
                  )}
                </Button>
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  )
}